/**
 * 将路由列表转为树型结构化
 * @param {*} data 
 */
function formatRouterTree(data) {
  /**
   * console.log(userRouters);
   * [
   *   {id: 2, pid: 0, path: '/course', name: 'Course', title: '课程管理'},
   *   {id: 3, pid: 2, path: 'operate', name: 'CourseOperate', link: '/course/operate', …}，
   *   {id: 6, pid: 0, path: '/student', name: 'Student', title: '学生管理'}，
   *   {id: 7, pid: 6, path: 'operate', name: 'StudentOperate', link: '/student/operate', …}
   * ]
   */

  //将parents分开
  let parents = data.filter(p => p.pid === 0),
    children = data.filter(c => c.pid !== 0);

  dataToTree(parents, children);

  //递归处理
  function dataToTree(parents, children) {
    //遍历所有parents
    parents.map((p) => {
      //遍历所有children
      children.map((c, i) => {
        //证明某项children是parents的儿子
        if (c.pid === p.id) {
          //以下操作都为了递归时写：

          //深拷贝复制一份c
          let _c = JSON.parse(JSON.stringify(children));
          //删除遍历出来的c
          _c.splice(i, 1);
          //再次递归
          dataToTree([c], _c);

          if (p.children) {
            //增加children属性并把children存入
            p.children.push(c);
          } else {
            //不存在时
            p.children = [c];
          }

        }
      });
    });
  }

  //处理parents
  return parents;

}

/**
 * 生成树状结构路由配置对象
 * @param {*} userRouters 格式化后的后端路由列表数据
 */
function generatorRouter(userRouters) {
  let newRouters = userRouters.map((r) => {
    let routes = {
      path: r.path,
      name: r.name,
      component: () => import(`@/views/${r.name}.vue`)
    }

    if (r.children) {
      //深度递归增加children属性和属性值 
      routes.children = generatorRouter(r.children);
    }

    return routes;
  });

  return newRouters;
}


export {
  formatRouterTree,
  generatorRouter
}